<template>
  <div :id="chartId">
  </div>
</template>


<script>
  import echarts from 'echarts/lib/echarts'
  import 'echarts/lib/chart/pie'
  import 'echarts/lib/component/grid'
  import 'echarts/lib/component/tooltip'
  import 'echarts/lib/component/title'

  export default {
    name: 'pie-doughnut',

    props: {
      chartId: { // DOM 容器的 id
        type: String,
        required: true,
      },
      redraw: { // 是否重绘
        type: Boolean,
        default: true,
      },
      showTitle: { // 是否显示标题
        type: Boolean,
        default: false,
      },
      chartTitle: { // 图表标题
        type: String,
        default: '',
      },
      chartName: { // 图表名称
        type: String,
        required: true,
      },
      colors: { // 图表的颜色
        type: Array,
        default: () => {
          return ['#23c88e', '#ff7956', '#ffc74a']
        },
      },
      chartData: { // 图表所需数据
        type: Array,
        default: () => {
          return []
        },
      },
    },

    watch: {
      // redraw: 'drawChart',
      chartData: {
        deep: true,
        handler: 'drawChart',
      },
    },

    methods: {
      drawChart() {
        const chart = echarts.init(document.getElementById(this.chartId))
        const option = {
          color: this.colors,
          title: {
            show: this.showTitle,
            text: this.chartTitle,
            x: 'center',
            y: 'center',
            textStyle: {
              fontWeight: 'normal',
              color: this.colors[0],
              fontSize: '30',
            },
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
            confine: true,
          },
          series: [
            {
              name: this.chartName,
              type: 'pie',
              radius: ['70%', '85%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center',
                },
                emphasis: {
                  show: false,
                },
              },
              labelLine: {
                normal: {
                  show: false,
                },
              },
              data: this.chartData,
            },
          ],
        }
        chart.setOption(option)
      },
    },

    mounted() {
      this.drawChart()
    },
  }
</script>
